package com.work.yshop.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.widget.ImageView;

import com.work.yshop.R;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 图片加载工具类
 */
public class ImageLoader {

    /**
     * 加载图片
     * @param context 上下文
     * @param imagePath 图片路径
     * @param imageView 目标ImageView
     */
    public static void loadImage(Context context, String imagePath, ImageView imageView) {
        if (imagePath == null || imagePath.isEmpty()) {
            imageView.setImageResource(R.drawable.ic_add_photo);
            return;
        }
        
        try {
            // 尝试从文件路径加载
            File file = new File(imagePath);
            if (file.exists()) {
                Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
                imageView.setImageBitmap(bitmap);
                return;
            }
            
            // 尝试从URI加载
            Uri uri = Uri.parse(imagePath);
            if (uri != null) {
                imageView.setImageURI(uri);
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            imageView.setImageResource(R.drawable.ic_add_photo);
        }
    }
    
    /**
     * 从输入流加载图片
     * @param inputStream 输入流
     * @return Bitmap对象
     */
    public static Bitmap loadBitmapFromStream(InputStream inputStream) {
        try {
            return BitmapFactory.decodeStream(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 从文件加载图片
     * @param filePath 文件路径
     * @return Bitmap对象
     */
    public static Bitmap loadBitmapFromFile(String filePath) {
        try {
            FileInputStream fis = new FileInputStream(filePath);
            Bitmap bitmap = BitmapFactory.decodeStream(fis);
            fis.close();
            return bitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
} 